package inabit.data.expression.arithmetic;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import inabit.base.WorkingMemory;
import inabit.data.InabitMethod;
/**Executes an inabit method to a set of parameters. It evaluates each arithmetic expression
 * passed by parameter and forms a list of string parameters with the result values, then executes
 * the method passing the list of result strings as parameter
 * @author Rafael Rocha*/
public class MethodExpression implements ArithmeticExpression{
	private InabitMethod method;
	private ArithmeticExpression[] params;
	
	public MethodExpression(InabitMethod method, ArithmeticExpression... params) {
		this.method = method;
		this.params = params;
	}

	@Override
	public String getResult(WorkingMemory wm) {
		String[] parameters = new String[params.length];
		for(int i = 0; i < params.length; i++) {
			parameters[i] = params[i].getResult(wm);
		}
		String result;
		try {
			result = method.evaluate(parameters);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return result;
	}

	@Override
	public String stringForm() {
		String param = "( ";
		for(int i = 0; i < params.length; i++){
			if(i > 0) {
				param += ", ";
			}
			param += params[i].stringForm();
		} 
		param += " )";
		
		return method.getName() + param;
	}

	@Override
	public Collection<String> getReferenced() {
		List<String> all = new ArrayList<String>();
		for(int i = 0; i < params.length; i++) {
			all.addAll(params[i].getReferenced());
		}
		return all;
	}

	@Override
	public boolean isLeaf() {
		return true;
	}
}
